package org.yzh.web.service.impl;

import com.github.dozermapper.core.Mapper;
import com.ling5821.mtime.Mtime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yzh.web.mapper.VehicleTravelMapper;
import org.yzh.web.model.entity.VehicleTravelDO;
import org.yzh.web.model.vo.DeviceOnlineInfo;
import org.yzh.web.model.vo.VehicleTravelQuery;
import org.yzh.web.service.VehicleTravelService;

import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @author lsj
 * @date 2021/1/15 16:12
 */
@Service
public class VehicleTravelServiceImpl implements VehicleTravelService {

    @Autowired
    private VehicleTravelMapper vehicleTravelMapper;

    @Autowired
    private Mapper dozerMapper;

    @Override
    public List<VehicleTravelDO> find(VehicleTravelQuery query) {
        return vehicleTravelMapper.find(query);
    }

    @Override
    public Optional<VehicleTravelDO> findUnique(String deviceId, String plateNo, LocalDate date) {
        return find(VehicleTravelQuery.builder().deviceId(deviceId).plateNo(plateNo).date(date).build()).stream().findFirst();
    }

    @Override
    public int insert(VehicleTravelDO record) {
        return batchInsert(Collections.singletonList(record));
    }

    @Override
    public int batchInsert(List<VehicleTravelDO> records) {
        return vehicleTravelMapper.batchInsert(records);
    }

    @Override
    public int updateTravelTime(DeviceOnlineInfo onlineInfo) {
        if (onlineInfo == null) {
            return 0;
        }
        Optional<VehicleTravelDO> recordOp = this.findUnique(onlineInfo.getDeviceId(), onlineInfo.getPlateNo(), LocalDate.now());
        /* 计算成秒数 */
        int travelTime = (int)(onlineInfo.getOfflineTime() - onlineInfo.getOnlineTime()) / 1000;
        if (travelTime < 0) {
            travelTime = 0;
        }

        if (recordOp.isPresent()) {
            VehicleTravelDO record = recordOp.get();
            record.setTravelTime(record.getTravelTime() + travelTime);
            return this.update(record);
        } else {
            VehicleTravelDO record = dozerMapper.map(onlineInfo, VehicleTravelDO.class);
            record.setDate(Mtime.toLocalDateOfEpochMilli(onlineInfo.getOnlineTime()));
            record.setTravelMileage(0.0);
            record.setTravelTime(travelTime);
            return this.insert(record);
        }
    }

    @Override
    public int update(VehicleTravelDO record) {
        return vehicleTravelMapper.update(record);
    }
}
